<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/3/20
 * Time: 上午11:58
 *
 *
 * 功能：标记预售7天发货，但是过了7天还没发货的订单需要发送企业微信通知
 *
 *
 */


//已弃用

ini_set('display_errors', 1);
ini_set('memory_limit', -1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\GoodsExtendInfo as mGoodsExtendInfo;
use Biz\model\trade\OrderPackage as mOrderPackage;
use Biz\service\ShopInfo as sShopInfo;
use Doraemon\amqp\Queue as aQueue;
use Doraemon\service\Member as sMember;
use Biz\cache\OrderHelper as cOrderHelper;

//获取所有未发货订单
//用户下单后开始计时，超过前台预计发货时间仍然没有发货（以商家上传物流单号时间点为准）系统提醒客服


$nowTime = date('Y-m-d H:i:s');

//获取现货时间的最小时间点
$minHour = min(mGoodsExtendInfo::$shippingTimeList[mGoodsExtendInfo::SHIPPING_TIME_TYPE_SPOT]);

$stopPayTime = date('Y-m-d H:i:s', time() - $minHour * 3600);


$where = [
    'pay_time[<=]' => $stopPayTime,
    'status' => [mOrder::STATUS_WAIT_SEND, mOrder::STATUS_SEND_PART_OUT]
];

$orderList = mOrder::select('*', $where);

if (empty($orderList)) {
    throw new \Exception('无数据');
}

foreach ($orderList as $orderInfo) {
    //一个订单一个订单的处理
    $whereSkuIds = [];

    //如果是部分发货，则需要把已发货的skuid排除
    if ($orderInfo['status'] == mOrder::STATUS_SEND_PART_OUT) {

        $skuIds = mOrderPackage::getAllPackageSkuIds($orderInfo['order_no']);

        if (empty($skuIds)) {
            continue;
        }

        $whereSkuIds['sku_id[!]'] = $skuIds;

    }

    //查询所有未发货的skuid
    $orderGoods = mOrderGoods::select('*', array_merge($whereSkuIds, [
        'order_no' => $orderInfo['order_no'],
        'refund_amount' => 0
    ]));


    if (!empty($orderGoods)) {
        $goodsIds = array_unique(array_column($orderGoods, 'goods_id'));

        logWrite(sprintf("有未发货的skuid order_no=%s list=%s \n", $orderInfo['order_no'], print_r($goodsIds, true)));

        checkGoodsAndSendMsg($goodsIds, $orderInfo);
    }
}

function checkGoodsAndSendMsg($goodsIds, $orderInfo)
{
    $noticeInfo = [];
    $payTime = $orderInfo['pay_time'];
    $nowTime = time();
    $goodsList = mGoodsExtendInfo::select(['goods_id', 'shipping_time'], [
        'goods_id' => $goodsIds,
        'shipping_time_type' => mGoodsExtendInfo::SHIPPING_TIME_TYPE_SPOT,
    ]);

    logWrite(sprintf("判断是否有现货，且有未发货的skuid order_no=%s row=%s \n", $orderInfo['order_no'], count($goodsList)));


    if (empty($goodsList)) {
        return false;
    }

    $goodsShipTimes = array_column($goodsList, 'shipping_time', 'goods_id');

    foreach ($goodsShipTimes as $goodsId => $shipTime) {

        $shouldShipTime = strtotime($payTime) + $shipTime * 3600;

        //如果到了该发货的时间而没有发，那么就构造通知信息
        if ($nowTime > $shouldShipTime) {
            $noticeInfo = [
                "order_no" => $orderInfo['order_no'],
                "add_time" => $orderInfo['addtime'],
                'shop_id' => $orderInfo['shop_id'],
                'is_package_delivery' => $orderInfo['is_package_delivery'],
                'should_shiptime' => date('Y-m-d H:i:s', $shouldShipTime),
                'user_message' => $orderInfo['message'],
                'uid' => $orderInfo['uid']
            ];

            logWrite(sprintf("组装待发信息成功 order_no=%s noticeInfo=%s \n", $orderInfo['order_no'], print_r($noticeInfo, true)));

            break;
        }
    }

    if (!empty($noticeInfo)) {
        sendMsg($noticeInfo);
    }

}


function sendMsg($noticeInfo)
{
    //无需重复发送
    $canSend = cOrderHelper::canSendAgainShipTimeOutToWxNotice($noticeInfo['order_no']);

    logWrite(sprintf("判断是否是重复发送 order_no=%s noticeInfo=%s cansend=%d \n", $noticeInfo['order_no'], print_r($noticeInfo, true), $canSend));

    if (!$canSend) {
        return false;
    }

    $shopInfo = sShopInfo::getShopInfo($noticeInfo['shop_id'], ['info']);

    $memberInfo = sMember::getUserInfoByUid($noticeInfo['uid']);

    $content = vsprintf('［发货超时提醒］%s 的订单：%s 买家昵称:%s  %s  下单时间:%s 预计发货时间:%s 用户备注:%s 超过发货时间，请跟进处理。', [
        $shopInfo['name'],
        $noticeInfo['order_no'],
        $memberInfo['nick'],
        $noticeInfo['is_package_delivery'] ? '部分商品' : '全部商品',
        $noticeInfo['add_time'],
        $noticeInfo['should_shiptime'],
        $noticeInfo['user_message']

    ]);


    cOrderHelper::sendShipTimeOutToWxNotice($noticeInfo['order_no']);

    logWrite(sprintf("发送通知 order_no=%s noticeInfo=%s cansend=%d \n", $noticeInfo['order_no'], print_r($noticeInfo, true), $canSend));

    aQueue::insertQueue("queue/Wechatnotice/toTag", [
        "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_SHIP_TIMEOUT,
        "content" => $content
    ], aQueue::QUEUE_BIZ);
}

function logWrite($msg)
{
    $nowTime = date('Y-m-d H:i:s');

    echo $nowTime . "    " . $msg;
}
